<?php
/**
 * Created by PhpStorm.
 * User: Frings
 * Date: 2017-09-10
 * Time: 21:22
 */

namespace app\models;


use app\librarys\DbCacheUtility;

/**
 * 余额支付
 * Class BalancePay
 * @package app\models
 */
class BalancePay
{

    /**
     * 获取平台入驻支付金额
     * @param $merchant_id
     * @param $message
     * @param int $month_sum
     * @return bool
     */
    public static function getPayMerchantGroup($merchant_id, &$message, $month_sum = 1)
    {
        $sql = 'SELECT t0.merchant_id,t1.monthly_amount FROM t_merchant_group t0 INNER JOIN t_merchant_group_config t1 ON t1.id = t0.merchant_group_id WHERE t0.merchant_id = :merchant_id ';
        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':merchant_id', $merchant_id);
        $item = DbCacheUtility::queryOne($cmd);
        if ($item == null) {
            $message = '未找到商户信息';
            return false;
        }

        $amount = $item['monthly_amount'] * $month_sum;
        return $amount;
    }

    /**
     * 平台入驻支付
     * @param $merchant_id
     * @param $message
     * @param int $month_sum
     * @return bool
     */
    public static function payMerchantGroup($merchant_id, &$message, $month_sum = 12, $mount_amount = 5)
    {
        $sql = 'SELECT * FROM t_merchant WHERE id = :merchant_id ';
        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':merchant_id', $merchant_id);
        $item = DbCacheUtility::queryOne($cmd);
        if ($item == null) {
            $message = '未找到商户信息';
            return false;
        }

        $amount = $mount_amount * $month_sum;

        //获取商户余额
        $balance = self::getMerchantBalance();
        if ($balance < $amount) {
            $message = '商户余额不足';
            return false;
        }

        $connection = \Yii::$app->db;
        $transaction = $connection->beginTransaction();

        $result = false;

        try {
            //修改余额金额
            $merchant_id = Merchant::getCurrentMerchant()['id'];
            $sql = 'UPDATE t_merchant SET amount = amount - :amount WHERE id = :id';
            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':id', $merchant_id);
            $cmd->bindValue(':amount', $amount);
            DbCacheUtility::execute($cmd);
            //修改商户平台
            $sql = 'UPDATE t_merchant SET rent_begin_datetime = IF(rent_begin_datetime IS NULL ,NOW(),rent_begin_datetime),
                        rent_end_datetime = IF(rent_end_datetime IS NULL ,date_add(now(),interval :month_sum MONTH),date_add(rent_end_datetime,interval :month_sum MONTH)),
                        rent_amount = :rent_amount
                    WHERE id = :merchant_id';
            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':merchant_id', $merchant_id);
            $cmd->bindValue(':month_sum', $month_sum);
            $cmd->bindValue(':rent_amount', $amount);
            DbCacheUtility::execute($cmd);

            $sql = 'INSERT INTO t_merchant_pay_record(id,merchant_id,amount,pay_mode,type,origin_id)
                    VALUES(uuid(),:merchant_id,:amount,3,:type,:origin_id)';
            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':merchant_id', $merchant_id);
            $cmd->bindValue(':amount', $amount);
            $cmd->bindValue(':type', 1);
            $cmd->bindValue(':origin_id', $merchant_id);
            DbCacheUtility::execute($cmd);

            $transaction->commit();
            $result = true;
        } catch (\Exception $e) {
            $transaction->rollBack();
        }

        return $result;

    }


    /**
     * 获取广告红包现金支付金额
     * @param $ad_id
     * @param $message
     * @return bool
     */
    public static function getPayAdCashGiftAmount($ad_id, &$message)
    {
        $sql = 'SELECT * FROM t_ad_cash_gift WHERE ad_id = :ad_id AND pay_status = 0';
        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':ad_id', $ad_id);
//        var_dump($cmd->rawSql);
        $item = DbCacheUtility::queryOne($cmd);

        if ($item == null) {
            $message = '广告不存在或者是不为未支付状态';
            return false;
        }

        $amount = $item['one_cash'] * $item['count'];
        return $amount;
    }

    /**
     * 广告红包现金支付
     * @param $ad_id
     * @param $message
     * @return bool
     */
    public static function payAdCashGift($ad_id, &$message)
    {
        $sql = 'SELECT * FROM t_ad_cash_gift WHERE ad_id = :ad_id AND pay_status = 0';
        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':ad_id', $ad_id);
        $item = DbCacheUtility::queryOne($cmd);

        if ($item == null) {
            $message = '广告不存在或者是不为未支付状态';
            return false;
        }

        $amount = $item['one_cash'] * $item['count'];

        //获取商户余额
        $balance = self::getMerchantBalance();
        if ($balance < $amount) {
            $message = '商户余额不足';
            return false;
        }

        $connection = \Yii::$app->db;
        $transaction = $connection->beginTransaction();

        $result = false;

        try {
            //修改余额金额
            $merchant_id = Merchant::getCurrentMerchant()['id'];
            $sql = 'UPDATE t_merchant SET amount = amount - :amount WHERE id = :id';
            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':id', $merchant_id);
            $cmd->bindValue(':amount', $amount);
            DbCacheUtility::execute($cmd);

            //修改个人领取红包金额的金额
            $platform_rake_fee_rate = \Yii::$app->params['platform_rake_fee_rate'];
            $platform_rake_fee = $amount * $platform_rake_fee_rate;


            $agent_rake_fee_rate = \Yii::$app->params['agent_rake_fee_rate'];
            $agent_rake_fee = $platform_rake_fee * $agent_rake_fee_rate;

            $agent_id = Agent::getAgentIdByMerchantId($merchant_id);
            if ($agent_id) {
                $sql = 'INSERT INTO t_agent_rake_fee(ad_id, agent_id, pay_mode, agent_rake_fee, agent_rake_fee_rate)
                        VALUES (:ad_id, :agent_id, 3, :agent_rake_fee, :agent_rake_fee_rate)';
                $cmd = \Yii::$app->db->createCommand($sql);
                $cmd->bindValue(':ad_id', $ad_id);
                $cmd->bindValue(':agent_id', $agent_id);
                $cmd->bindValue(':agent_rake_fee', $agent_rake_fee);
                $cmd->bindValue(':agent_rake_fee_rate', $agent_rake_fee_rate);

                DbCacheUtility::execute($cmd);

                $platform_rake_fee = $platform_rake_fee - $agent_rake_fee;
            }


            $sql = 'INSERT INTO t_platform_rake_fee(ad_id, pay_mode, platform_rake_fee, platform_rake_fee_rate) 
                    VALUES (:ad_id, 3, :platform_rake_fee, :platform_rake_fee_rate)';
            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':ad_id', $ad_id);
            $cmd->bindValue(':platform_rake_fee', $platform_rake_fee);
            $cmd->bindValue(':platform_rake_fee_rate', $platform_rake_fee_rate);
            DbCacheUtility::execute($cmd);


            //修改用户领取红包的总金额
            $amount = $amount - $platform_rake_fee;
            if($agent_id){
                $amount = $amount - $agent_rake_fee;
            }

            //修改广告红包现金状态
            $sql = 'UPDATE t_ad_cash_gift SET pay_status = 1,one_cash =:one_cash,one_cash_old = :one_cash_old WHERE ad_id = :ad_id';
            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':ad_id', $ad_id);
            $cmd->bindValue(':one_cash', floor($amount / $item['count']*100)/100);
            $cmd->bindValue(':one_cash_old', $item['one_cash']);
            DbCacheUtility::execute($cmd);

            $sql = 'UPDATE t_ad SET status = 40 WHERE id = :id';
            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':id', $ad_id);
            DbCacheUtility::execute($cmd);

            $sql = 'INSERT INTO t_merchant_pay_record(id,merchant_id,amount,pay_mode,type,origin_id)
                    VALUES(uuid(),:merchant_id,:amount,3,:type,:origin_id)';
            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':merchant_id', $merchant_id);
            $cmd->bindValue(':amount', $amount);
            $cmd->bindValue(':type', 3);
            $cmd->bindValue(':origin_id', $ad_id);
            DbCacheUtility::execute($cmd);

            $transaction->commit();
            $result = true;
        } catch (\Exception $e) {
            $transaction->rollBack();
        }
        return $result;
    }

    /**
     * 余额支付特殊行业广告认证费用
     * @param $ad_id
     * @param $message
     * @param int $amount
     * @return bool
     */
    public static function payAdSpecial($ad_id, &$message, $amount = 300)
    {
        $sql = 'SELECT * FROM t_ad_special WHERE ad_id = :ad_id AND pay_status = 0';
        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':ad_id', $ad_id);
        $item = DbCacheUtility::queryOne($cmd);

        if ($item == null) {
            $message = '未找到该条特殊行业广告信息';
            return false;
        }

        //获取商户余额
        $balance = self::getMerchantBalance();
        if ($balance < $amount) {
            $message = '商户余额不足';
            return false;
        }

        $connection = \Yii::$app->db;
        $transaction = $connection->beginTransaction();

        $result = false;
        try {
            //修改余额金额
            $merchant_id = Merchant::getCurrentMerchant()['id'];
            $sql = 'UPDATE t_merchant SET amount = amount - :amount WHERE id = :id';
            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':id', $merchant_id);
            $cmd->bindValue(':amount', $amount);
            DbCacheUtility::execute($cmd);

            //修改特殊行业广告认证费用状态
            $sql = 'UPDATE t_ad_special SET pay_status = 1 WHERE ad_id = :ad_id';
            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':ad_id', $ad_id);
            DbCacheUtility::execute($cmd);

            $sql = 'UPDATE t_ad SET status = 10 WHERE id = :id';
            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':id', $ad_id);
            DbCacheUtility::execute($cmd);

            $sql = 'INSERT INTO t_merchant_pay_record(id,merchant_id,amount,pay_mode,type,origin_id)
                    VALUES(uuid(),:merchant_id,:amount,3,:type,:origin_id)';
            $cmd = \Yii::$app->db->createCommand($sql);
            $cmd->bindValue(':merchant_id', $merchant_id);
            $cmd->bindValue(':amount', $amount);
            $cmd->bindValue(':type', 2);
            $cmd->bindValue(':origin_id', $ad_id);
            DbCacheUtility::execute($cmd);

            $transaction->commit();
            $result = true;
        } catch (\Exception $e) {
            $transaction->rollBack();
        }

        return $result;
    }


    /**
     * 获取当前登录商家的余额
     * @return mixed
     */
    public static function getMerchantBalance()
    {
        $merchant_id = Merchant::getCurrentMerchant()['id'];
        $sql = 'SELECT ifnull(amount,0) as amount  FROM t_merchant WHERE id = :id';
        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':id', $merchant_id);
        $balance = DbCacheUtility::queryScalar($cmd);
        return $balance;
    }


}